import assert from 'assert';
class CrudService {
  constructor(db, ...arg) {
    this.db = db;
    this.arg = arg;
  }

  /**
     * 保存记录
     * @param tableName
     * @param values
     * @returns {*}
     */
  async save(tableName, values) {
    if (values instanceof Object && !Array.isArray(values)) {
      return this.db[tableName].create(values);
    } else {
      return false;
    }
  }

  /**
     * 根据id更新记录
     * @param tableName
     * @param values
     * @param id
     * @returns {*}
     */
  async updateById(tableName, values, id) {
    if (values instanceof Object && !Array.isArray(values)) {
      return this.db[tableName].update(values, {where: {id: id}});
    }
  }

  /**
     * 自定义where条件更新记录
     * @param tableName
     * @param values
     * @param where
     * @returns {*}
     */
  async updateByWhere(tableName, values, where) {
    if (values instanceof Object && !Array.isArray(values)) {
      return this.db[tableName].update(values, {where: where});
    }
  }

  /**
     * 自定义where条件查询，返回原始对象数据，不带任何sequelize生命周期实例属性
     * @param tableName
     * @param where
     */
  async findAll(tableName = '', where = {}, attributes = []) {
    assert(Array.isArray(attributes), 'attributes must be a Array');
    assert(typeof tableName === 'string', 'tableName must be a String');
    assert(ObjectUtils.isObject(where), 'where must be a Object');
    const option = {
      raw: true
    };
    if (Object.keys(where).length > 0) {
      option.where = where;
    }

    if (attributes.length > 0) {
      option.attributes = attributes;
    }
    return this.db[tableName].findAll(option);
  }

  /**
     * 原生sql查询
     * @param sql
     * @returns {*}
     */
  async querySql(sql) {
    return this.db.sequelize.query(sql, {type: this.db.sequelize.QueryTypes.SELECT});
  }

  /**
     *保存多条数据
     * @param tableName  模型
     * @param array 数组
     * @returns {*}
     */
  async saveMany(tableName, array) {
    if (!Array.isArray(array)) {
      return false;
    }
    return this.db[tableName].bulkCreate(array);
  }

  /**
     * 根据id删除数据
     * @param tableName
     * @param id
     * @returns {*}
     */
  async deleteById(tableName, id) {
    return this.db[tableName].destroy({where: {id: id}});
  }

  /**
     * 删除所有数据
     * @param tableName
     * @returns {*}
     */
  async deleteAll(tableName) {
    return this.db[tableName].destroy();
  }
}

module.exports = CrudService;
